package cn.ywang.framework;

import cn.ywang.Model.Member;

import java.sql.*;

/**
 * @Auther: BeatificWang
 * @Date: 2018/11/17 19:40
 */
public class SimpleExecutor implements Executor {

	@Override
	public <T> T query(String statement, String parameter) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		Member member = new Member();
		try {
			// 加载驱动
			Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
			// 建立连接
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?user=root&password=123456");
			// 准备语句集
			statement = String.format(statement, Integer.parseInt(parameter));
			preparedStatement = connection.prepareStatement(statement);
			// 执行语句
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				member.setId(resultSet.getInt("id"));
				member.setName(resultSet.getString("name"));
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (preparedStatement != null) {
				try {
					preparedStatement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return (T) member;
	}
}
